package cn.imusic.config;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider;
import com.netflix.discovery.DefaultEurekaClientConfig;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;

import cn.imusic.discovery.registry.impl.EurekaRegistration;
import cn.imusic.discovery.registry.impl.EurekaServiceRegistry;
import cn.imusic.discovery.registry.impl.ImusicDataCenterInstanceConfig;
import cn.imusic.discovery.registry.impl.ImusicEurekaClient;


@Configuration
public class EurekaClientConfiguration {
  
  @Autowired
  EurekaRegistration eurekaRegistration;
  @Autowired
  EurekaServiceRegistry eurekaServiceRegistry;
  
  @PostConstruct
  public void initRegister() {
    System.out.println("init register.");
    eurekaServiceRegistry.register(eurekaRegistration);
  }

  @Bean
  public EurekaInstanceConfig eurekaInstanceConfig() {
    return new ImusicDataCenterInstanceConfig(true);
  }

  @Bean
  public ApplicationInfoManager eurekaApplicationInfoManager(
      EurekaInstanceConfig eurekaInstanceConfig) {
    return new ApplicationInfoManager(eurekaInstanceConfig,
        new EurekaConfigBasedInstanceInfoProvider(eurekaInstanceConfig).get());
  }

  @Bean
  public EurekaClientConfig eurekaClientConfig() {
    return new DefaultEurekaClientConfig();
  }
  

  @Bean(destroyMethod = "shutdown")
  public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config) {
    return new ImusicEurekaClient(manager, config);
  }


  @Bean
  public EurekaRegistration eurekaRegistration(EurekaClient eurekaClient,
      EurekaInstanceConfig instanceConfig, ApplicationInfoManager applicationInfoManager) {
    return EurekaRegistration.builder(instanceConfig).with(applicationInfoManager)
        .with(eurekaClient).build();
  }

  @Bean
  public EurekaServiceRegistry eurekaServiceRegistry() {
    return new EurekaServiceRegistry();
  }
}
